<?php

namespace Iwester\Http\Controllers\Admin\Manage;

use Iwester\Http\Controllers\Admin\BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Http\Model\User\Permission;
use Iwester\Http\Model\User\Role;
use Iwester\Http\Model\User\User;
use Iwester\Http\Requests\UserUpdateRequest;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Config\Banner;
use Iwester\Http\Requests\UserCreateRequest;


class AdminUserController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * user 列表
     * @return Response
     */
    public function user(Request $request)
    {
        $users = User::orderBy('id', 'desc')->paginate(15);
        return view('iwester::admin.manage.user.user', [
            'users'=> $users
        ]);
    }

    /**
     * 添加用户
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('iwester::admin.manage.user.create');
    }

    /**
     * 保存
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(UserCreateRequest $request)
    {
        try {
            \DB::beginTransaction();
            $data = $request->get('user', []);
            $data['uuid'] = \Faker\Provider\Uuid::uuid();
            $data['password'] = bcrypt($data['password']);
            $user = User::create($data);
            \DB::commit();
            return ['code' => 200, 'message' => '设置成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => '保存失败！'];
        }
    }

    /**
     * 编辑用户
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        $user = User::find($id);
        return view('iwester::admin.manage.user.edit', [
            'user'=> $user,
        ]);
    }

    /**
     * 更新用户信息
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(UserUpdateRequest $request)
    {
        try {
            \DB::beginTransaction();
            $id = $request->input('id', 0);
            $data = $request->get('user', []);
            $user = User::find($id);
            $user->update($data);
            \DB::commit();
            return ['code' => 200, 'message' => '设置成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => '保存失败！'];
        }
    }

    /**
     * 修改用户 状态 -  冻结
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function change(Request $request, $id)
    {
        try {
            \DB::beginTransaction();
            $isDelete = $request->get('is_delete', 0);
            $user = User::find($id);
            $user->is_delete = $isDelete;
            $user->save();
            \DB::commit();
            return ['code' => 200, 'message' => '操作成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }

    /**
     * 用户分配角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function role(Request $request, $id)
    {
        $user = User::find($id);
        $roles = Role::all();
        return view('iwester::admin.manage.user.role', [
            'user'=> $user,
            'roles'=> $roles
        ]);
    }

    /**
     * 保存用户- 角色关系
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function roleStore(Request $request, $id)
    {
        try {
            \DB::beginTransaction();
            $user = User::find($id);
            $roles = $request->get('roles',[]);
            $user->syncRoles($roles);
            \DB::commit();
            return redirect()->to(route('manage.user'))->with(['status'=>'更新用户角色成功']);
        } catch (\Exception $e) {
            \DB::rollBack();
            return  redirect()->route('manage.user.role', ['id'=> $id])->with('errors', ['系统错误，保存失败']);
        }
    }

    /**
     * 用户分配权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permission(Request $request, $id)
    {
        $user = User::find($id);
        $permissions = Permission::permission();
//        $userPermissions = $user->getAllPermissions()->pluck('name');
//        $userPermissions->search($four->name) !== false
        // 展示继承角色的权限
        $permissionsViaRoles = $user->getPermissionsViaRoles()->pluck('name');
        return view('iwester::admin.manage.user.permission', [
            'user'=> $user,
            'permissions'=> $permissions,
            'permissionsViaRoles'=> $permissionsViaRoles,
//            'userPermissions'=> $userPermissions,
        ]);
    }

    /**
     * 保存用户- 权限关系
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function permissionStore(Request $request, $id)
    {
        try {
            \DB::beginTransaction();
            $user = User::find($id);
            $data = $request->get('permissions', []);
            if (empty($data)){
                $user->permissions()->detach();
            }else{
                $user->syncPermissions($data);
            }
            \DB::commit();
            return redirect()->to(route('manage.user'))->with(['status'=>'已更新用户直接权限']);
        } catch (\Exception $e) {
            \DB::rollBack();
            return  redirect()->route('manage.user.permission', ['id'=> $id])->with('errors', ['系统错误，保存失败']);
        }
    }
}
